import logging

import pymysql
from pymysql.constants import CLIENT


class DBUtil(object):

    def __init__(self, host="localhost", user="root", password="root",
                 database="dbname", port=3306, charset="utf8"):
        self.connect = pymysql.connect(host=host, user=user, password=password,
                                       database=database, port=port, charset=charset,
                                       client_flag=CLIENT.MULTI_STATEMENTS)

        self.cursor = self.connect.cursor()

    def __del__(self):
        self.cursor.close()
        self.connect.close()

    def dql_all(self, sql):
        num = self.cursor.execute(sql)

        if (num):
            return self.cursor.fetchall()
        else:
            return None

    def dml_sql(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            logging.info(f'执行错误：{e}')
            self.connect.rollback()
        else:
            self.connect.commit()


if __name__ == '__main__':
    dbUtil = DBUtil(host='121.43.169.97', port=3306,
                    user='root', password='Itcast_p2p_20191228',
                    database='czbk_member')

    phone = '15900001561'

    sql1 = f"delete i.* from mb_member_info i inner join mb_member m on m.id = i.member_id where m.phone in ('{phone}');"
    sql2 = f"delete l.* from mb_member_login_log l inner join mb_member m on m.id=l.member_id where m.phone in ('{phone}')"
    sql3 = f"delete from mb_member where phone in ('{phone}')"
    sql4 = f"delete from mb_member_register_log where phone in ('{phone}')"

    print(dbUtil.dml_sql(sql1))
    print(dbUtil.dml_sql(sql2))
    print(dbUtil.dml_sql(sql3))
    print(dbUtil.dml_sql(sql4))
